<style lang="less">
@import "../styles/common.less";
</style>

<template>
  <div class="HeightAlldiv">
    <Row :gutter="10" class="row">
      <Card>
        <div class="HeightAlldiv-div" id="HeightAlldiv-div">
          <!-- 创建文本编辑器 -->
          <div id="editor-div" :style="{width: 100 + '%',height: ckEditorContHeight + 'px'}"></div>

          <input type="file" id="checkImg" style="display: none" accept="image/*" @change="addFile" />

          <div class="Button-footer">
            <Button class="Button" type="primary" @click="saveFun">保存</Button>
          </div>
        </div>
      </Card>
    </Row>
  </div>
</template>
<style>
#editor-div {
  overflow-y: auto;
}

#editor-div.ql-container,
#editor-div .ql-editor {
  height: auto;
}

.Button-footer {
  width: 100%;
  height: 40px;
  text-align: right;
  line-height: 38px;
  padding-top: 10px;
}

.Button-footer .Button {
  margin-right: 10px;
}
</style>
<script>
import Util from "../../libs/util";
import Utils from "../../libs/mod.utils";

export default {
  components: {},
  data() {
    return {
      ckEditorContHeight: 350,
      editorOption: null,
      saveLoading: false,
      code: "",
      dataObj: {},
      content: ""
    };
  },
  computed: {},
  beforeMount: function() {
    var _this = this;
  },
  beforeDestroy: function() {
    var _this = this;
  },
  created: function() {
    var _this = this;
    _this.getData();
  },
  mounted: function() {
    var _this = this;
    _this.init();
    _this.checkLeave();
  },
  methods: {
    checkLeave: function() {
      var _this = this;
      window.onbeforeunload = function(e) {
        var e = window.event || e;
        e.returnValue = "确定离开当前页面吗？";
      };
    },
    saveFun: function() {
      var _this = this;
      var content = _this.editorOption
        ? _this.editorOption.container.firstChild.innerHTML
        : "";
      if (content) {
        _this.content =
          content == "<p>&nbsp;</p>" || content == "<p><br></p>" ? "" : content;
      }
      if (_this.content == "") {
        Utils.showToast.error(_this, "请输入内容!");
        return false;
      }
      var dataObj = _this.dataObj;
      dataObj.content = _this.content; // 富文本
      console.log(dataObj);
      return;
      let params = {
        url: "/contact/update",
        type: Util.method.post,
        data: dataObj,
        success: _successFun
      };
      Util.ajax(_this, params);

      function _successFun(res) {
        if (res.result == 0) {
          Utils.showToast.success(_this, "保存成功!");
        } else {
          Utils.showToast.error(_this, "保存失败!");
        }
      }
    },
    // 获取数据
    getData: function() {
      var _this = this;
      let params = {
        url: "/contact/query",
        type: Util.method.post,
        data: {},
        success: _successFun
      };
      Util.ajax(_this, params);

      function _successFun(res) {
        if (res.result == 0) {
          var _data = res.data || {};
          var content = _data.content || "";
          var data = _data.data || "";
          var dataObj = {};
          if (data) {
            dataObj = Utils.toJson(data);
          }
          _this.dataObj = dataObj;
          _this.content = content;
          _this.setEditorOption();
        } else {
          _this.dataObj = {};
          _this.content = "";
          _this.setEditorOption();
          Utils.showToast.error(_this, "查询失败");
        }
      }
    },
    // 设置富文本内容
    setEditorOption: function() {
      var _this = this;
      if (_this.editorOption) {
        _this.editorOption.container.firstChild.innerHTML = _this.content;
      } else {
        _this.init();
      }
    },
    // 初始化富文本
    init: function() {
      var _this = this;
      this.$nextTick(() => {
        var ckEditorContHeight =
          parseInt($("#HeightAlldiv-div").height()) - 44 - 80;
        _this.ckEditorContHeight = ckEditorContHeight;

        //          var BackgroundClass = Quill.import('attributors/class/background');
        //          var ColorClass = Quill.import('attributors/class/color');
        //          var SizeStyle = Quill.import('attributors/style/size');
        //          Quill.register(BackgroundClass, true);
        //          Quill.register(ColorClass, true);
        //          Quill.register(SizeStyle, true);

        var toolbarOptions = [
          ["bold", "italic", "underline", "strike"], // toggled buttons
          ["blockquote", "code-block"],
          [{ header: [1, 2, 3, 4, 5, 6, false] }],
          [{ header: 1 }, { header: 2 }], // custom button values
          [{ list: "ordered" }, { list: "bullet" }],
          //          [{'script': 'sub'}, {'script': 'super'}],      // superscript/subscript
          //          [{'indent': '-1'}, {'indent': '+1'}],          // outdent/indent
          //          [{'direction': 'rtl'}],                         // text direction
          //          [{'size': ['small', false, 'large', 'huge']}],  // custom dropdown
          //          [{'color': []}, {'background': []}],          // dropdown with defaults from theme
          //          [{'font': []}],
          [{ align: [] }],
          ["image", "clean"] // remove formatting button
        ];

        _this.editorOption = new Quill("#editor-div", {
          modules: {
            toolbar: toolbarOptions
          },
          placeholder: "编辑内容...",
          theme: "snow" // bubble snow
        });

        if (_this.content) {
          _this.editorOption.container.firstChild.innerHTML = _this.content;
        }

        let toolbar = _this.editorOption.getModule("toolbar");
        toolbar.addHandler("image", () => {
          document.getElementById("checkImg").click();
        });

        $("#editor-div .ql-editor").css(
          "minHeight",
          ckEditorContHeight - 10 + "px"
        );
      });
    },
    // 上传图片
    addFile: function() {
      let _this = this;
      let inputObj = document.getElementById("checkImg");
      let fileObj = inputObj.files[0];
      if (typeof fileObj == "undefined" || fileObj.size <= 0) {
        Utils.showToast.error(_this, "请选择图片!");
        return false;
      }
      let fileName = fileObj.name;
      let fileTypeStr = fileObj.type;
      let fileTypeArr = fileTypeStr.split("/");
      let fileType = fileTypeArr[0].trim();
      let to_url = "";
      if (fileType == "image") {
        to_url = "/file/addImage";
      } else {
        to_url = "/file/addFile";
      }
      let formFile = new FormData();
      formFile.append("file", fileObj); //加入文件对象
      let params = {
        url: to_url,
        type: Util.method.post,
        data: formFile,
        success: _successFileUpload
      };
      Util.ajax(_this, params);

      function _successFileUpload(res) {
        let resData = res.data ? res.data : null;
        if (resData != undefined && resData != null && resData != "") {
          var urlp = resData.urlp;
          const range = _this.editorOption.getSelection();
          if (range) {
            _this.editorOption.insertEmbed(range.index, "image", urlp);
          }
        }
      }
    }
  }
};
</script>
